#!/bin/sh 

# name:			audio multi converter
# brief:		convert files in current directory
# license:	http://www.gnu.org/licenses/lgpl-3.0.txt
# author:		manifest

usage() {
	echo "USAGE: `basename $0` [-i input file extension] [-o output format] [-ab bitrate_param] [-ar frequency_param] [-ac channels_param] [-ss start_param] [-t duration_param]";
	exit 1;
}

error() {
	echo "ERROR: $1"
	usage
}

input_file_ext=
output_format=
params=

while :
do
	case "$1" in
		-i)		shift; input_file_ext="$1";;
		-o)		shift; output_format="$1";;
		-ab)	shift; params="$params -ab $1";;
		-ar)	shift; params="$params -ar $1";;
		-ac)	shift; params="$params -ac $1";;
		-ss)	shift; params="$params -ss $1";;
		-t)		shift; params="$params -t $1";;
		-*)	usage;;
		*)	break;;
	esac
	shift
done

if [ ! "$input_file_ext" ]; then
	input_file_ext=*
fi

if [ ! "$output_format" ]; then
	error "output format not set"
fi

mkdir source;
for file in *.$input_file_ext; do
	
	#move source file
	mv "$file" source;
	
	#convert
	audiocsh -i "source/$file" $params -o "$output_format";

	#check errors
	if [ ! $? -eq 0 ]; then
		error "internal error";
		#move soure back
		mv "source/$file" .;
	fi

done;

